import glob
import json
import os
import time
import unittest
from datetime import date, timedelta

import pandas as pd

from common.utils import FileUtil
from common.utils.ExcelUtil import xlsx_merge
from fake_useragent import UserAgent

from autoTask.operaitonAid.taobao.correlation_analysis_module.relatedAnalysis import RelatedAnalysis
from autoTask.operaitonAid.taobao.get_marke_goods_module.get_goods import GetProductInfo
from autoTask.operaitonAid.taobao.search_ranking_module.searchRank import SearchRank
from autoTask.operaitonAid.taobao.through_train_module.add_keywords_price import AddCommodity
from autoTask.operaitonAid.taobao.get_store_info_module.get_store_info import StoreInfo
from autoTask.core.taskMapping import task_operaiton_gjc_run
from autoTask.operaitonAid.test_param_dict import task_operaiton_gjc_dict, task_operaiton_gjc_list
from autoTask.taobao.taobao_login import Login
from common.utils.web_page_util import create_page, Tap
from request.utils.request import Request
import requests
from autoTask.core.TaskThread import execute_task
from autoTask.operaitonAid.taobao.title_maker_module.title_creator import ParseExcelToTitle


param_ = {
    "taskId": "4",
    "taskName": "生意参谋-关键词-行业词",
    "param": {
        "account": "中山杰特电器:星星",
        "password": "yzt123456",
        # "account": "赫巴兹直销企业店",
        # "password": "zty1213",
        "searchContent": "炒锅",
        "isOperationTitle": True,
        "isAutoAppendKeyWord": True,
        "isTestExecute": True,
        "dataWord": "搜索词",
        "salesTimeModule": "day",
        "salesTime": "2023-06-03|2023-06-03",
        "tableTopic": [
            "蜂窝"
        ],
        "keywordList": ["空气炸锅商用",
                        "空气炸锅烤箱一体",
                        "炸串锅"
                        ],
        "dealValue": 1000,
        "payNum": 30,
        "price": 128,
        "dealNum": 10000,
        "hotIndex": 1,
        "searchNum": 10000,
        "payRate": 10,
        "numOfPay": 500,
        "matchesType": "精准匹配",
        "targetProductMap": [
            {
                "productId": "671036943564",
                "competing1": "684927851841",
                "competing2": "556907022467",
                "titlePrefix": "格洛恩316蜂窝",
                "titleSuffix": "炒锅",
                "titleMaxLength": 60,
                "ignoreCuts": []
            }
        ],
        "rmEnglish": True,
        "percent": 99,
        "priceCap": 1,
        "dateCycle": 7,
        "isAppendCompeting": True,
        "competingMinVisits": 10,
        "competingMinRoi": 0
    }
}


class MyTestCase(unittest.TestCase):
    def test_something(self):
        self.assertEqual(True, False)  # add assertion here

    def test_SearchRank(self):
        params = {
            "account": "中山杰特电器:星星",
            "password": "yzt123456",
            "searchContent": "炒锅",
            "dateCycle": 7,
            "dataWord": "搜索词",
        }
        category = params["searchContent"]
        datalist = SearchRank(params)()
        keywords = datalist["关键词"].tolist()
        keywords_obj = RelatedAnalysis(params, keywords)()
        # print(keywords_obj)
        # data_dict = {"keywordList": keywords_obj}

        Request("post", uri="public/operationAid/KeyWord/add", params={
            "categoryName": category,
            "dataList": keywords_obj
        }, req_title="测试", req_is_log=True).send()

    def test_AddCommodity(self):
        # page = create_page()
        param = {
            "keywordList": [
                "空气炸锅商用",
                "空气炸锅烤箱一体",
                "炸串锅"
            ],
            "account": "中山杰特电器:星星",
            "password": "yzt123456",
            "matchesType": "精准匹配",
            "productId": 671036943564,
            "percent": 60,
            "priceCap": 1,
            "isTestExecute": True
        }
        AddCommodity(param).add_keywords()
        # page.quit()

    def test(self):
        page = create_page(is_refresh=False)
        # /html/body/ul/li[2]/div/button/span
        # page("x://div[@class='copy-btn-wrap']//button[contains(@class, 'el-dropdown__caret-button')]/span").hover()
        # Tap(page("x:/html/body/ul[contains(@class, 'el-dropdown-menu--small')]//li[2]/div/button"), by_js=True,
        #     msg="点击默认按钮失败")()
        ylmf_turnover = page("x://div[contains(@class, 'ahPAoa_OI')]")("tx:成交金额").next().text
        print(ylmf_turnover)

    def test_get_data(self):
        param = dict(param_.get('param'))
        product_list = GetProductInfo(param).get_product_info()
        # print(product_list[0].img.show())
        for product in product_list:
            print(
                f"商品ID:{product.id}--数据类型:{type(product.id)}"
                f"\n商品标题:{product.title}--数据类型:{type(product.title)}"
                f"\n商品价格:{product.price}--数据类型:{type(product.price)}"
                f"\n商品销量:{product.sales}--数据类型:{type(product.sales)}"
                f"\n商品库存:{product.stock}--数据类型:{type(product.stock)}"
                f"\n商品质量:{product.quality}--数据类型:{type(product.quality)}"
                f"\n商品创建时间:{product.createtime}--数据类型:{type(product.createtime)}"
                f"\n商品图片:{product.img_base64}--数据类型:{type(product.img_base64)}"
            )
            # print(product.img_base64)
            # id: int
            # title: str
            # price: float
            # img_url: str
            # img: Image
            # stock: str
            # sales: float
            # quality: str
            # createtime: datetime

    def test_store_info(self):
        param = dict(param_.get('param'))
        StoreInfo(param).sales_time_set()

    def test_task_operaiton_gjc_run(self):
        print(task_operaiton_gjc_dict)
        task_operaiton_gjc_run(task_operaiton_gjc_dict)

    def test_task_operaiton_flask(self):
        url = 'http://127.0.0.1:19376/root/operaiton'
        data = json.dumps(task_operaiton_gjc_list)
        response = requests.post(url, data=data)
        print(response.status_code)  # 打印状态码
        print(response.text)  # 打印响应内容

    def test_flask_TaskThread(self):
        # task_snapshot = json.dumps(task_operaiton_gjc_list, ensure_ascii=False)
        # print(task_snapshot)
        task_snapshot = task_operaiton_gjc_list
        # for snapshot in task_snapshot:
        #     print(snapshot)
        # json.loads(snapshot)
        # print(task_snapshot)
        execute_task(task_snapshot)
        # execute_task(task_operaiton_gjc_list)

    def test_new_title(self):
        ParseExcelToTitle(product_id=671036943564, new_title="运营助手 关键词", tb_username="中山杰特电器:星星",
                          tb_password="yzt123456", is_test_execute=True)()

    def test_request_api(self):
        account = "赫巴兹直销企业店:数据"
        password = "aa123456"
        page = create_page(is_refresh=True)
        page, _ = Login(account, password, page=page).execute(url="https://subway.simba.taobao.com")
        cookies = ','.join([f"{key}={value}" for key, value in page.cookies.items()])
        headers = {
            "User-Agent": UserAgent().random,
            "Cookie": cookies,
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Referer": "https://subway.simba.taobao.com/index.jsp",
            "Origin": "https://subway.simba.taobao.com"
        }
        datas = {
            "queryParam": str({"startDate": "2023-06-10", "endDate": "2023-06-10", "effect": -1})
        }
        response = requests.post(
            url="https://subway.simba.taobao.com/openapi/param2/1/gateway.subway/rpt/rptCampaignByDay$",
            data=datas, headers=headers)

        print(response.json())
        params = {
            "dateType": "day",
            "dateRange": "2023-06-10|2023-06-10"
        }
        get_data = requests.get(
            url="https://sycm.taobao.com/portal/coreIndex/getShopMainIndexes.json", headers=headers, params=params)
        print(get_data.json())

    def test_product_single(self):
        param1 = {
            "account": "赫巴兹直销企业店:数据",
            "password": "aa123456"
        }
        ProductSingleAnalysis(param1)()

    def test_xlsl_merge(self):
        dw_path = os.path.join(FileUtil.get_project_root(), "DownloadData/sycm_table/flow_source/source_excel/")
        output_path = os.path.join(FileUtil.get_project_root(), "DownloadData/sycm_table/flow_source/result_excel/")
        for path in [dw_path, output_path]:
            # 判断文件夹路劲是否存在，不存在则创建
            os.makedirs(path, exist_ok=True)
        #
        # 使用 glob 模块查找所有 .xlsx 文件
        xlsx_files = glob.glob(os.path.join(dw_path, '*.xlsx'))
        xlsx_merge(xlsx_files=xlsx_files, sheet_name="流量来源合并", output_path=output_path,
                   file_name="流量来源合并.xlsx", header_parent=True, row_height=30)
        print(FileUtil.get_project_root())

    def test_day(self):
        # 获取当前日期
        yesterday = date.today() - timedelta(days=1)
        print(type(yesterday))

        # 计算30天后的日期
        future_date = yesterday - timedelta(days=30)

        print("昨天日期:", yesterday)
        print("30天前的日期:", future_date)


if __name__ == '__main__':
    unittest.main()
